package model

import (
	"context"
	"fmt"
	sq "github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"xialou_platform/app/requestx"
)

var _ CourseModel = (*customCourseModel)(nil)

type (
	// CourseModel is an interface to be customized, add more methods here,
	// and implement the added methods in customCourseModel.
	CourseModel interface {
		courseModel
		FindListCount(ctx context.Context, keyword string, online uint64) int64
		FindList(ctx context.Context, page *requestx.ListReq, online uint64) ([]*Course, error)
	}

	customCourseModel struct {
		*defaultCourseModel
	}
)

// NewCourseModel returns a model for the database table.
func NewCourseModel(conn sqlx.SqlConn, c cache.CacheConf) CourseModel {
	return &customCourseModel{
		defaultCourseModel: newCourseModel(conn, c),
	}
}

func (m *defaultCourseModel) FindListCount(ctx context.Context, keyword string, online uint64) int64 {
	selectBuilder := sq.Select("count(1)").From(m.table)
	if len(keyword) != 0 {
		selectBuilder = selectBuilder.Where(sq.Like{"title": fmt.Sprint("%", keyword, "%")})
	}
	if online == 1 {
		selectBuilder = selectBuilder.Where(sq.Eq{"online": true})
	} else if online == 2 {
		selectBuilder = selectBuilder.Where(sq.Eq{"online": false})
	}

	query, args, err := selectBuilder.PlaceholderFormat(sq.Dollar).ToSql()
	if err != nil {
		return 0
	}
	var count int64
	err = m.QueryRowNoCacheCtx(ctx, &count, query, args...)
	if err != nil {
		return 0
	}
	return count

}

func (m *defaultCourseModel) FindList(ctx context.Context, page *requestx.ListReq, online uint64) ([]*Course, error) {
	selectBuilder := sq.Select(courseRows).From(m.table).Limit(page.Limit()).Offset(page.Offset())
	if len(page.Keyword) != 0 {
		selectBuilder = selectBuilder.Where(sq.Like{"title": fmt.Sprint("%", page.Keyword, "%")})
	}
	if online == 1 {
		selectBuilder = selectBuilder.Where(sq.Eq{"online": true})
	} else if online == 2 {
		selectBuilder = selectBuilder.Where(sq.Eq{"online": false})
	}
	query, args, err := selectBuilder.OrderBy("sort,create_time desc").PlaceholderFormat(sq.Dollar).ToSql()
	if err != nil {
		return nil, err
	}
	var resp []*Course
	err = m.QueryRowsNoCacheCtx(ctx, &resp, query, args...)
	return resp, err
}
